<template>
	<view>
		<!-- 收银台 -->
		<view class="edgeInsetTop"></view>
		<view class="wanl-pay">
			<view class="price-box">
				<text class="text-df">{{order_no}}</text>
				<text class="wanl-pip text-price margin-top-sm">{{price}}</text>
			</view>
			<view class="list-box">
				<view class="item" v-for="(item, index) in payList" :key="index">
					<text :class="'wlIcon-'+ item.type +'-pay'"></text>
					<view class="action">
						<text class="title wanl-pip">{{item.name}}</text>
						<view v-if="item.type == 'balance'">
							<text v-if="isbalance">可用余额 ￥{{user.money}}</text>
							<text v-else>余额不足，可用余额 ￥{{user.money}}</text>
						</view>
						<view v-else>{{item.describe}}</view>
					</view>
					<view class="radio text-xxl" v-if="item.state" @tap="onSelect(index)">
						<text v-if="item.select" class="wlIcon-xuanze-danxuan wanl-orange"></text>
						<text v-else class="wlIcon-xuanze wanl-gray-light"></text>
					</view>
					<view class="radio text-xxl" v-else>
						<text class="wlIcon-xuanze-danxuan wanl-gray-light"></text>
					</view>
				</view>
				<!-- 好友代付 -->
				<view class="item" v-if="goodsType == 'goods' && coupon_price == 0">
					<button class="flex_y_center c9  btnshare" style="width: 100%;" open-type="share">
						<view style="width: 98rpx;" class="tal">
							<u-icon size="52" name="https://img.aibbyp.com/wechatUser/yhdf.png"></u-icon>
						</view>
						<view class="flex1">
							<view class="f32 c6 tal">
								用户代付 <text class="cf64 f28 ml12"> ￥<text class="f36 fb">{{paymentBehalf.price}}</text>
								</text>
							</view>
							<view class="f24 tal" v-if="user.level == 2 || user.level == 3 ">
								用户付款后，预估工匠可获取差价 <text class="cf64">￥{{paymentBehalf.difference_price}}</text>
							</view>
						</view>
						<view class="">
							<u-icon name="arrow-right"></u-icon>
						</view>
					</button>

				</view>

				<!-- 助力 -->
				<view v-if="assistShow" class="flex_y_center c9 item"
					@click="$wanlshop.to('/pages/user/assist/assist')">
					<view style="width: 98rpx;">
						<image style="width: 64rpx;height: 64rpx;" src="https://img.aibbyp.com/wechatUser/yqhy.png"
							mode="">
						</image>
					</view>
					<view class="flex1">
						<view class="f32 c6">
							邀请好友助力
						</view>
						<view class="f24">
							超低价格起购
						</view>
					</view>
					<view class="">
						<u-icon name="arrow-right"></u-icon>
					</view>
				</view>
				<!-- #ifdef MP-WEIXIN -->
				<!-- #endif -->
			</view>

			<view v-if="disabled">
				<button class="mix-btn wanl-bg-redorange"> <text
						class="wlIcon-jiazai wlIconfont-spin margin-right-xs"></text>正在支付中... </button>
			</view>
			<view v-else>
				<button :disabled="btnLoading" v-if="payNum == 1" class="mix-btn wanl-bg-redorange" @tap="confirm()">
					确认支付 </button>
				<button :disabled="btnLoading" v-else class="mix-btn wanl-bg-redorange" @tap="confirm()"> 合并支付 </button>
			</view>
			<view class="footer text-center">
				<view class="text-sm" v-if="order_pay_no">{{order_type === 'groups' ? '拼团':''}}交易号：{{order_pay_no}}
				</view>
				<!-- <view> © 万联支付</view> -->
			</view>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex';
	export default {
		data() {
			return {
				option: '',
				btnLoading: false,
				token: '',
				disabled: false,
				price: '0.00',
				isbalance: false,
				order_type: 'goods',
				order_no: '',
				order_pay_no: '',
				payNum: 1, // 支付方式 独立支付-合并支付
				payList: [],
				assistShow: false,
				paymentBehalf: {
					price: '0.00',
					difference_price: '0.00',
				},
				order_ids: [],
				goodsType: null,
				coupon_price: 0,
			}
		},
		computed: {
			...mapState(['user'])
		},
		watch: {
			price(val, newval) {
				if (val <= parseFloat(this.$store.state.user.money)) {
					console.log(val, '---->jiage')
					this.isbalance = true;
					this.getPayment();
				}

			}
		},
		// 添加分享钩子
		onShareAppMessage() {
			console.log(this.order_ids);
			this.getsharePay()
			return {
				title: '我选好材料啦，请你帮我付个款吧~',
				path: `/pages/user/money/paymentBehalf?order_ids=${this.order_ids.join(',')}`,
				imageUrl: 'https://img.aibbyp.com/wechatUser/xhcl.png', // 替换为实际分享图片URL
				success: (res) => {
					console.log('分享成功', res);
					// 分享成功后的操作
				},
				fail: (err) => {
					// 分享失败后的操作
				}
			};
		},

		async onLoad(option) {

			this.option = option
			console.log(option);

			let res = await this.$api.post({
				url: '/wanlshop/pay/getBalance',
			})
			this.$store.commit('user/setUserInfo', {
				money: res
			});

			// 获取支付列表
			this.getPayment();
			let ids = []
			if (option.data) {
				var sum = 0,
					sum1 = 0,
					data = JSON.parse(option.data),
					order_ids = [];
				console.log(data);
				this.goodsType = JSON.parse(option.data)[0].type
				this.coupon_price = data.reduce((a, b) => {
					return this.$wanlshop.bcadd(a, b.coupon_price)
				}, '0')
				this.order_ids = data.map(a => a.order_id)
				if (data.length <= 1) {
					this.price = data[0].price;
					this.order_type = data[0].type;
					this.order_no = `${data[0].type == 'groups' ? '拼团':''}订单号：${data[0].order_no}`;
					this.order_pay_no = data[0].pay_no;
					this.order_id = data[0].order_id;
					this.paymentBehalf.price = data[0].take_price
					this.paymentBehalf.difference_price = this.$wanlshop.bcsub(data[0].take_price, data[0].price)
					if (data[0].help) {
						this.assistShow = true
						ids.push(data[0].order_id)
						this.$store.commit('statistics/getgoods_ids', ids)
					}
				} else {
					console.log(data, '---->')
					data.forEach(item => {
						if (item.price) {
							sum = this.$wanlshop.bcadd(sum, item.price);
						}
						if (item.take_price) {
							sum1 = this.$wanlshop.bcadd(sum1, item.take_price);
						}
						order_ids.push(item.order_id);
						if (item.help) {
							this.assistShow = true
							ids.push(item.order_id)
							this.$store.commit('statistics/getgoods_ids', ids)
						}
					});
					this.paymentBehalf.price = sum1
					this.paymentBehalf.difference_price = this.$wanlshop.bcsub(sum1, sum)
					this.price = sum;
					this.order_id = order_ids;
					this.payNum = data.length;
					this.order_no = '合并支付 ' + data.length + '个订单';
				}
				this.token = option.token;
			} else if (option.order_id) { //我的订单待支付 单个支付
				if (option.help) {
					this.assistShow = true
					ids.push(option.order_id)
					this.$store.commit('statistics/getgoods_ids', ids)
				}
				uni.showLoading({
					title: '结算中...'
				});
				this.paygetPay(option, 0)

			} else if (option.ids && option.dffk) { //代付之后多个合并订单 -- 自己付款
				console.log(1);
				this.paygetPay(option, 1)
			} else {
				console.log('非法访问');
			}
		},
		methods: {

			paygetPay(option, num) { //我的订单待支付 单个支付
				let url = '/wanlshop/pay/getPay',
					order_id = option.order_id

				if (num == 1) {
					url = '/wanlshop/pay/getTakePay'
					order_id = option.ids.split(',')
				}
				this.$api.post({
					url: url,
					data: {
						order_id: order_id,
						order_type: option.order_type
					},
					success: res => {
						if (num == 1) {
							this.price = 0
							res.forEach(a => {
								this.price = this.$wanlshop.bcadd(this.price, a.price);
								this.order_type = a.order_type
								this.order_no = `订单号:${a.order_no}`
								this.order_pay_no = a.pay_no;
							})
							this.order_id = res.map(a => a.order_id);
							uni.hideLoading();
							return
						}
						uni.hideLoading();
						this.token = res.token;
						this.price = res.price;
						this.order_type = res.order_type;
						this.order_no = `${res.order_type == 'groups' ? '拼团':''}订单号：${res.order_no}`;
						this.order_pay_no = res.pay_no;
						this.order_id = res.order_id;
						this.assistShow = res.help
					}
				});
			},
			getsharePay() {
				this.$api.post({
					url: '/wanlshop/order/sharePay',
					data: {
						order_id: this.order_ids,
					},
					success: res => {}
				})
			},
			getUrlCode() {

				// 截取url中的code方法
				var url = location.search;
				// this.winUrl = url;
				var theRequest = new Object();
				if (url.indexOf('?') != -1) {
					var str = url.substr(1);
					var strs = str.split('&');
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
					}
				}
				return theRequest;

			},
			getPayment() {
				console.log('d')
				let method = 'wap';
				// #ifdef APP-PLUS
				method = 'app';
				// #endif
				// #ifdef MP-BAIDU
				method = 'mini';
				// #endif
				// #ifdef MP-WEIXIN
				method = 'miniapp';
				// #endif
				// #ifdef MP-ALIPAY
				method = 'mini';
				// #endif
				// #ifdef MP-QQ
				method = 'mini';
				// #endif
				this.payList = [{
					name: '余额支付',
					describe: '',
					type: 'balance',
					method: 'balance',
					state: this.isbalance ? true : false, // 是否可用
					select: this.isbalance ? true : false // 是否选中
				}];
				// #ifdef H5
				if (this.$jssdk.isWechat()) {
					// 基本完成,后端未测试,没有完善回调，1.0.8 版本暂时屏蔽
					this.payList.push({
						name: '微信支付',
						describe: '推荐使用微信支付',
						type: 'jssdk',
						method: method,
						state: true,
						select: this.isbalance ? false : true
					});
				} else {
					this.payList.push({
						name: '支付宝',
						describe: '',
						type: 'alipay',
						method: method,
						state: true,
						select: false
					}, {
						name: '微信支付',
						describe: '推荐使用微信支付',
						type: 'wechat',
						method: method,
						state: true,
						select: this.isbalance ? false : true
					});
				}
				// #endif
				// #ifndef H5
				uni.getProvider({
					service: "payment",
					success: (e) => {
						// e.provider.push('wxpay')
						e.provider.map((value) => {
							if (value == 'alipay') {
								this.payList.push({
									name: '支付宝',
									describe: '',
									type: value,
									method: method,
									state: true,
									select: false
								});
							} else if (value == 'wxpay') {
								this.payList.push({
									name: '微信支付',
									describe: '推荐使用微信支付',
									type: 'wechat',
									method: method,
									state: true,
									select: this.isbalance ? false : true
								});
							} else if (value == 'baidu') {
								this.payList.push({
									name: '百度收银台',
									describe: '',
									type: value,
									method: method,
									state: true,
									select: false
								});
							} else if (value == 'appleiap') {
								// this.payList.push({name: 'Apple支付',describe: '',type: 'apple',method: method,state: true,select: false});
							}
						})
					}
				});
				// #endif
				console.log(this.payList)
			},
			//确认支付
			confirm() {

				this.btnLoading = true
				let data = null;
				if (this.disabled) {
					return;
				}
				this.payList.map((value, index, array) => {
					if (value.select) {
						data = value;
					} else {
						return;
					}
				});

				// 判断支付是否存在
				if (!data) {
					uni.showModal({
						content: "请选择支付方式",
						showCancel: false
					});
					return;
				} else {
					this.disabled = true;
					// 获取小程序code
					// #ifdef MP
					uni.login({
						success: (e) => {
							this.wanlPay(data, e.code);
						},
						fail: (e) => {
							uni.showModal({
								content: "无法获取微信code,原因为: " + e.errMsg,
								showCancel: false
							})
						}
					})
					// #endif
					// #ifndef MP
					this.wanlPay(data);
					// #endif
				}
			},
			async wanlPay(data, code = null) {
				if (this.option.craftsman) {
					this.$api.post({
						url: '/worker/recruit/payRecruit',
						data: {
							order_type: this.order_type,
							type: data.type,
							method: data.method,
							code: code,
							order_ids: this.order_id,
							token: this.token
						},
						success: res => {
							this.wanlPaySuccess(data, res)
						},
						fail: res => {
							console.log('支付失败');
							this.disabled = false
							this.btnLoading = false
						}
					});
					return

				}
				this.$api.post({
					url: '/wanlshop/pay/payment',
					data: {
						order_type: this.order_type,
						type: data.type,
						method: data.method,
						code: code,
						order_id: this.order_id,
						token: this.token
					},
					success: res => {
						this.wanlPaySuccess(data, res)
					},
					fail: res => {
						console.log('支付失败');
						this.disabled = false
						this.btnLoading = false
					}
				});
			},
			wanlPaySuccess(data, res) {
				// 余额支付/小程序支付
				if (data.type == 'balance') {
					this.$store.commit('user/setUserInfo', {
						money: this.$wanlshop.bcsub(this.$store.state.user.money, this
							.price)
					});
					this.paySuccess();
				}
				// 微信 H5支付
				if (data.type == 'wechat' && data.method == 'wap') {
					// 1.0.8升级 延迟弹出
					setTimeout(() => {
						uni.showModal({
							content: '请确认微信支付是否已完成',
							confirmText: '已完成',
							cancelText: '重新支付',
							success: response => {
								if (response.confirm) {
									this.paySuccess();
								} else if (response.cancel) {
									this.confirm();
								}
							}
						});
					}, 2000);
					// 异步查询是否支付成功
					window.location.href = res;
				}
				// 支付宝 H5支付
				if (data.type == 'alipay' && data.method == 'wap') {
					this.disabled = false;
					if (this.order_type === 'goods') {
						this.$store.commit('statistics/order', {
							pay: this.$wanlshop.bcsub(this.$store.state.statistics.order
								.pay, this.payNum),
							delive: this.$wanlshop.bcadd(this.$store.state.statistics.order
								.delive, this.payNum)
						});
					}
					document.write(res);
				}
				// 微信小程序支付
				if (data.type == 'wechat' && data.method == 'miniapp') {
					uni.requestPayment({
						appId: res.appId,
						nonceStr: res.nonceStr,
						package: res.package,
						paySign: res.paySign,
						signType: res.signType,
						timeStamp: res.timeStamp,
						success: (e) => {
							this.paySuccess();
						},
						fail: (e) => {
							uni.showModal({
								content: "支付失败",
								showCancel: false
							})
						}
					})
				}
				// 微信JSSDK支付，返回的是配置
				if (data.type == 'jssdk' && data.method == 'wap') {
					this.$jssdk.wxpay({
						data: res,
						success: res => {
							this.paySuccess();
						},
						fail: err => {
							if (err.errMsg == "chooseWXPay:ok") {
								this.$wanlshop.msg('支付成功');
							} else if (err.errMsg == "chooseWXPay:cancel") {
								this.$wanlshop.msg('支付失败，取消支付');
							} else if (err.errMsg == "chooseWXPay:fail") {
								this.$wanlshop.msg('支付失败');
							}
							this.disabled = false;
							this.payErr()
						}
					})
				}
				// APP支付
				if ((data.type == 'alipay' || data.type == 'wechat') && data.method == 'app') {
					let provider = data.type;
					if (data.type == 'wechat') {
						provider = 'wxpay';
					}
					uni.requestPayment({
						provider: provider,
						orderInfo: res,
						success: (e) => {
							console.log("success", e);
							this.paySuccess();
						},
						fail: (e) => {
							uni.showModal({
								content: "支付失败",
								showCancel: false
							})
							this.payErr()
						},
						complete: () => {
							this.disabled = false;
						}
					})
				}

			},
			onSelect(key) {
				this.payList.map((value, index, array) => {
					if (index == key) {
						value.select = !value.select;
					} else {
						value.select = false;
					}
				});
			},
			// 支付成功
			paySuccess() {

				this.disabled = false;
				if (this.order_type === 'goods') {
					this.$store.commit('statistics/order', {
						pay: this.$store.state.statistics.order.pay - this.payNum,
						delive: this.$store.state.statistics.order.delive + this.payNum
					});
				}
				this.btnLoading = false
				if (this.option.craftsman) {
					this.$wanlshop.to(`/pages/craftsman/company/fabuchenggong?order_ids=${this.order_id}`);
					return
				}
				this.$wanlshop.to(`/pages/page/success?type=pay&order_type=${this.order_type ? this.order_type:'goods'}`);
			},
			payErr() {
				return;
				uni.showModal({
					title: '提示',
					content: '这是一个模态弹窗',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		}
	}
</script>

<style>
	.btnshare::after {
		display: none;
	}

	.btnshare {
		background: transparent;
		padding: 0;
		margin: 0;
		height: 100%;
		line-height: normal;
	}

	page {
		background-color: white;
	}

	radio-group {
		display: block;
	}
</style>